package com.morgan.maxfunding;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.util.Log;
import android.util.Xml;

class MyAsyncTask extends AsyncTask<String, Integer, Integer>{
	
	public static final int SEND_SUCCESS = 1;
	public static final int SEND_FAIL = -1;
	
	public static final int UPLOAD_SUCCESS = 2;
	public static final int UPLOAD_FAIL = -2;
	
	public static final int USB_SUCCESS = 3;
	public static final int USB_FAIL = -3;
	
	public static final int CONTACT_US_SUCCESS = 4;
	public static final int CONTACT_US_FAIL = -4;
	
	public static final int HELP_SUCCESS = 5;
	public static final int HELP_FAIL = -5;
	
	public static final int FIRST_FILE_UPLOAD_SUCCESS = 6;
	public static final int FIRST_FILE_UPLOAD_FAIL = -6;
	
	public static final String ACTION_SIGNUP = "signup";
	public static final String ACTION_FILE_UPLOAD = "upload";
	public static final String ACTION_USB = "usb";
	public static final String ACTION_LOGIN = "login";
	public static final String ACTION_CONTACT_US = "contact_us";
	public static final String ACTION_HELP = "help";
	public static final String ACTION_FILE_UPLOAD_FIRST = "first_upload";
	
	public static final String FROM_INDEX = "Index";
	public static final String FROM_COMPLETE = "Complete";
	
	public static final String SUCESS = "success";
    public Context parent;
    public ProgressDialog dlgLoading;
    
    public String strCurrentAction;
    

	public MyAsyncTask(Context _parent, String action) {
		parent = _parent;
		strCurrentAction = action;
	}
	
	@Override
	protected Integer doInBackground(String... params) {
		// TODO Auto-generated method stub
		int n = SEND_SUCCESS;
		
		strCurrentAction = params[0];
		
		if (params[0] == ACTION_SIGNUP) {
			n = signup();
		}
		if (params[0] == ACTION_FILE_UPLOAD) {
			n = fileUpload(params[1], params[2], params[3]);
		}
		if (params[0] == ACTION_USB) {
			n = usb();
		}
		if (params[0] == ACTION_LOGIN) {
			
		}
		if (params[0] == ACTION_CONTACT_US) {
			n = contactUs(params[1], params[2], params[3], params[4]);
		}
		if (params[0] == ACTION_HELP) {
			n = helpProc(params[1]);
		}
		if (params[0] == ACTION_FILE_UPLOAD_FIRST) {
			n = firstFileUpload(params[1], params[2], params[3], params[4], params[5], params[6]);
		}
		return n;
	}
	
	@Override
	protected void onPreExecute() {
		
		dlgLoading = new ProgressDialog(parent);
		if (strCurrentAction.equals(ACTION_FILE_UPLOAD) ||strCurrentAction.equals(ACTION_FILE_UPLOAD_FIRST)) {
			dlgLoading.setMessage("\tUploading...");	
		} else {
			dlgLoading.setMessage("\tLoading...");
		}
    	
    	dlgLoading.setCanceledOnTouchOutside(false);
    	dlgLoading.setCancelable(false);
        dlgLoading.show();
	}

	protected void onPostExecute(Integer result){
		Log.e("HCW", "post_end");

		if (dlgLoading.isShowing()) {
			dlgLoading.dismiss();
		}

		if (result == SEND_SUCCESS) {
			NewSubmitActivity newSbmActivity = (NewSubmitActivity) parent;
			
			newSbmActivity.goNextPage();
		}
		
		if (result == SEND_FAIL) {
			NewSubmitActivity newSbmActivity = (NewSubmitActivity) parent; 
			newSbmActivity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
					" record in your mobile.\n Please try submit when having internet connection");
		}
		
		if (result == UPLOAD_FAIL) {
			CompleteActivity completeActivity = (CompleteActivity) parent;
			completeActivity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
					" record in your mobile.\n Please try submit when having internet connection");
		}
		if (result == UPLOAD_SUCCESS) {
			CompleteActivity completeActivity = (CompleteActivity) parent;
			completeActivity.showGeneralAlert("Upload Sucess!", "Your file has been uploaded.");
		}
		if (result == USB_FAIL) {
			if (GlobalData.personalInfo.nTypeUSB == 2) {
				UsbActivity2 usbActivity2 = (UsbActivity2) parent;
				usbActivity2.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
						" record in your mobile.\n Please try submit when having internet connection");
			}
			if (GlobalData.personalInfo.nTypeUSB == 3) {
				UsbActivity3 usbActivity3 = (UsbActivity3) parent;
				usbActivity3.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
						" record in your mobile.\n Please try submit when having internet connection");
			}
		}
		if (result == USB_SUCCESS) {
			if (GlobalData.personalInfo.nTypeUSB == 2) {
				UsbActivity2 usbActivity2 = (UsbActivity2) parent;
				usbActivity2.goNextPage();
			}
			if (GlobalData.personalInfo.nTypeUSB == 3) {
				UsbActivity3 usbActivity3 = (UsbActivity3) parent;
				usbActivity3.goNextPage();
			}
		}
		if (result == CONTACT_US_SUCCESS) {
			NewContactUsActivity activity = (NewContactUsActivity) parent;
			activity.completeSubmit();
		}
		if (result == CONTACT_US_FAIL) {
			NewContactUsActivity activity = (NewContactUsActivity) parent;
			activity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
					" record in your mobile.\n Please try submit when having internet connection");
		}
		if (result == HELP_SUCCESS) {
			if (parent instanceof NewIndexActivity) {
				NewIndexActivity activity = (NewIndexActivity) parent;
				activity.showGeneralAlert("", "Your form is submitted successfully.");
			}
			if (parent instanceof CompleteActivity) {
				CompleteActivity activity = (CompleteActivity) parent;
				activity.showGeneralAlert("", "Your form is submitted successfully.");
			}
		}
		if (result == HELP_FAIL) {
			if (parent instanceof NewIndexActivity) {
				NewIndexActivity activity = (NewIndexActivity) parent;
				activity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
						" record in your mobile.\n Please try submit when having internet connection");
			}
			if (parent instanceof CompleteActivity) {
				CompleteActivity activity = (CompleteActivity) parent;
				activity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
						" record in your mobile.\n Please try submit when having internet connection");
			}
		}
		if (result == FIRST_FILE_UPLOAD_FAIL) {
			FileUploadActivity activity = (FileUploadActivity) parent;
			activity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
					" record in your mobile.\n Please try submit when having internet connection");
		}
		if (result == FIRST_FILE_UPLOAD_SUCCESS) {
			FileUploadActivity activity = (FileUploadActivity) parent;
			activity.showGeneralAlert("Upload Sucessful!", "Your file has been uploaded.");
		}
//		parent.startActivity(new Intent(parent, CompleteActivity.class));
	}
	
	protected void onProgressUpdate(Integer... progress) {
//		Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG).show();
//    	dlgLoading.dismiss();
	}

	public Integer signup() {
		
		// Create a new HttpClient and Post Header
		HttpPost httppost = new HttpPost("http://maxfunding.com.au/mobileApp/CRMDB/mobile_proc.php");
//		HttpPost httppost = new HttpPost("http://192.168.1.101/Morgan/mobile_proc.php");

		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    int k = SEND_FAIL;
	    try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            
            nameValuePairs.add(new BasicNameValuePair("action", "signup"));
            nameValuePairs.add(new BasicNameValuePair("purpose", "business"));

            /// max_application
//            nameValuePairs.add(new BasicNameValuePair("device_id", GlobalData.strDeviceID));
            
            nameValuePairs.add(new BasicNameValuePair("app_LoanAmount", GlobalData.personalInfo.strLoanAmount));
            nameValuePairs.add(new BasicNameValuePair("app_PurposeOfLoan1", GlobalData.personalInfo.strPurposeOfLoan1));
            nameValuePairs.add(new BasicNameValuePair("app_PurposeSummary", GlobalData.personalInfo.strPurposeSummary));

            //////liability fields
            nameValuePairs.add(new BasicNameValuePair("app_BoardingRentingFee", GlobalData.personalInfo.strBoardingRentingCost));
            nameValuePairs.add(new BasicNameValuePair("app_LivingExpensesPayment", GlobalData.personalInfo.strLivingExpensesPayment));
            
            /// max_client
            nameValuePairs.add(new BasicNameValuePair("app_Title1", GlobalData.personalInfo.strTitle1));
            nameValuePairs.add(new BasicNameValuePair("app_FirstName1", GlobalData.personalInfo.strFirstName1));
            nameValuePairs.add(new BasicNameValuePair("app_MiddleName1", GlobalData.personalInfo.strMiddleName1));
            nameValuePairs.add(new BasicNameValuePair("app_Surname1", GlobalData.personalInfo.strSurname1));
            nameValuePairs.add(new BasicNameValuePair("app_Residency", GlobalData.personalInfo.strResidency));
            nameValuePairs.add(new BasicNameValuePair("app_DateOfBirth1", GlobalData.personalInfo.strDOB));
            nameValuePairs.add(new BasicNameValuePair("app_DriversLicence1", GlobalData.personalInfo.strDriversLicense1));
            nameValuePairs.add(new BasicNameValuePair("app_Mobile1", GlobalData.personalInfo.strMobilePhone1));
            nameValuePairs.add(new BasicNameValuePair("app_Phone1", GlobalData.personalInfo.strHomePhone1));
            nameValuePairs.add(new BasicNameValuePair("app_EMailAddress1", GlobalData.personalInfo.strEMailAddress));
            nameValuePairs.add(new BasicNameValuePair("app_ResidentialStatus1", GlobalData.personalInfo.strResidentialStatus));
            
            nameValuePairs.add(new BasicNameValuePair("app_ResidentialAddress1", GlobalData.personalInfo.strResidentialAddress1));
            nameValuePairs.add(new BasicNameValuePair("app_Suburb1", GlobalData.personalInfo.strSuburb1));
            nameValuePairs.add(new BasicNameValuePair("app_State1", GlobalData.personalInfo.strState1));
            nameValuePairs.add(new BasicNameValuePair("app_Postcode1", GlobalData.personalInfo.strPostcode1));
        	
            nameValuePairs.add(new BasicNameValuePair("app_NumberofDependant1", GlobalData.personalInfo.strNumberOfDependant1));
            nameValuePairs.add(new BasicNameValuePair("app_OtherPurpose", GlobalData.personalInfo.strOtherPurpose));
            
            nameValuePairs.add(new BasicNameValuePair("count_motor_vehicle", Integer.toString(GlobalData.personalInfo.countMotorVehicle)));
            nameValuePairs.add(new BasicNameValuePair("count_real_estate", Integer.toString(GlobalData.personalInfo.countRealState)));

            // Vehicle 1
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle1Value", GlobalData.personalInfo.strVehcieValue1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Make", GlobalData.personalInfo.strMotorMake1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Model", GlobalData.personalInfo.strMotorModel1));
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle1Owner", GlobalData.personalInfo.strVehicleOwner1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Finance", GlobalData.personalInfo.strMotorFinance1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Year", GlobalData.personalInfo.strMotorYear1));
            nameValuePairs.add(new BasicNameValuePair("Insurance1", GlobalData.personalInfo.strInsurance1));
            
            // Vehicle 2
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle2Value", GlobalData.personalInfo.strVehcieValue2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Make", GlobalData.personalInfo.strMotorMake2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Model", GlobalData.personalInfo.strMotorModel2));
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle2Owner", GlobalData.personalInfo.strVehicleOwner2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Finance", GlobalData.personalInfo.strMotorFinance2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Year", GlobalData.personalInfo.strMotorYear2));
            nameValuePairs.add(new BasicNameValuePair("Insurance2", GlobalData.personalInfo.strInsurance1));

            // PropertyValue 1(Real Estate1) 
            nameValuePairs.add(new BasicNameValuePair("app_Property1Value", GlobalData.personalInfo.strMarketValue1));
            nameValuePairs.add(new BasicNameValuePair("app_Property1Address", GlobalData.personalInfo.strPropertyAddress1));
            nameValuePairs.add(new BasicNameValuePair("app_morarr1", GlobalData.personalInfo.strMorarr1));
            nameValuePairs.add(new BasicNameValuePair("app_Property1Owner", GlobalData.personalInfo.strPropertyOwner1));
            nameValuePairs.add(new BasicNameValuePair("PropertyType1", GlobalData.personalInfo.strEstateType1));
            nameValuePairs.add(new BasicNameValuePair("Description1", GlobalData.personalInfo.strEstateDescription1));
            nameValuePairs.add(new BasicNameValuePair("LandSize1", GlobalData.personalInfo.strLandSize1));
            nameValuePairs.add(new BasicNameValuePair("Bedroom1", GlobalData.personalInfo.strBedrooms1));
            nameValuePairs.add(new BasicNameValuePair("Bathroom1", GlobalData.personalInfo.strBathrooms1));
            nameValuePairs.add(new BasicNameValuePair("MortgageOwing1", GlobalData.personalInfo.strOwingCreditLimit1));
            nameValuePairs.add(new BasicNameValuePair("MortgagePayment1", GlobalData.personalInfo.strMothlyPayment1));
            nameValuePairs.add(new BasicNameValuePair("MortgageLender1", GlobalData.personalInfo.strLender1));

            // PropertyValue 2(Real Estate2)
            nameValuePairs.add(new BasicNameValuePair("app_Property2Value", GlobalData.personalInfo.strMarketValue2));
            nameValuePairs.add(new BasicNameValuePair("app_Property2Address", GlobalData.personalInfo.strPropertyAddress2));
            nameValuePairs.add(new BasicNameValuePair("app_morarr2", GlobalData.personalInfo.strMorarr2));
            nameValuePairs.add(new BasicNameValuePair("app_Property2Owner", GlobalData.personalInfo.strPropertyOwner2));
            nameValuePairs.add(new BasicNameValuePair("PropertyType2", GlobalData.personalInfo.strEstateType2));
            nameValuePairs.add(new BasicNameValuePair("Description2", GlobalData.personalInfo.strEstateDescription2));
            nameValuePairs.add(new BasicNameValuePair("LandSize2", GlobalData.personalInfo.strLandSize2));
            nameValuePairs.add(new BasicNameValuePair("Bedroom2", GlobalData.personalInfo.strBedrooms2));
            nameValuePairs.add(new BasicNameValuePair("Bathroom2", GlobalData.personalInfo.strBathrooms2));
            nameValuePairs.add(new BasicNameValuePair("MortgageOwing2", GlobalData.personalInfo.strOwingCreditLimit2));
            nameValuePairs.add(new BasicNameValuePair("MortgagePayment2", GlobalData.personalInfo.strMothlyPayment2));
            nameValuePairs.add(new BasicNameValuePair("MortgageLender2", GlobalData.personalInfo.strLender2));
        	
            // Liabilities
        	
            // Persoanl loan
            nameValuePairs.add(new BasicNameValuePair("app_PersonalLoanOwing", GlobalData.personalInfo.strPersonalLoanOwing));
            nameValuePairs.add(new BasicNameValuePair("app_PersonalLoanPayment", GlobalData.personalInfo.strPersonalLoanPayment));
            nameValuePairs.add(new BasicNameValuePair("app_PersonalLoanBank", GlobalData.personalInfo.strPersonalLoanLender));
            
            // Business Loan
            nameValuePairs.add(new BasicNameValuePair("business_loan_owing", GlobalData.personalInfo.strBusinessLoanOwing));
            nameValuePairs.add(new BasicNameValuePair("business_loan_lender", GlobalData.personalInfo.strBusinessLoanLender));

            // Credit Card
            nameValuePairs.add(new BasicNameValuePair("credit_card_owing", GlobalData.personalInfo.strCreditCardOwing));
            nameValuePairs.add(new BasicNameValuePair("credit_card_lender", GlobalData.personalInfo.strCreditCardLender));
            
            //// Vehicle 1 owing
            nameValuePairs.add(new BasicNameValuePair("app_v1Owing", GlobalData.personalInfo.strVehicleOwing1));
            nameValuePairs.add(new BasicNameValuePair("app_v1Payment", GlobalData.personalInfo.strVehiclePayment1));
            nameValuePairs.add(new BasicNameValuePair("app_v1Lender", GlobalData.personalInfo.strVehicleLender1));
            
            //// Vehicle 2 owing
            nameValuePairs.add(new BasicNameValuePair("app_v2Owing", GlobalData.personalInfo.strVehicleOwing2));
            nameValuePairs.add(new BasicNameValuePair("app_v2Payment", GlobalData.personalInfo.strVehiclePayment2));
            nameValuePairs.add(new BasicNameValuePair("app_v2Lender", GlobalData.personalInfo.strVehicleLender2));
            
            //Emplyment details
            nameValuePairs.add(new BasicNameValuePair("app_TypeOfEmployment1", GlobalData.personalInfo.strEmploymentStatus));
            nameValuePairs.add(new BasicNameValuePair("app_TOE1", GlobalData.personalInfo.strEmploymentType));
            nameValuePairs.add(new BasicNameValuePair("app_TitleInOccupation1", GlobalData.personalInfo.strTitleOccupation));
            nameValuePairs.add(new BasicNameValuePair("app_BusinessName1", GlobalData.personalInfo.strEmployerName));
            nameValuePairs.add(new BasicNameValuePair("app_WorkPhone1", GlobalData.personalInfo.strHrContactNumber1));
        	
            ////Income details
            nameValuePairs.add(new BasicNameValuePair("app_IncomeAfterTax1", GlobalData.personalInfo.strIncomeAfterTax));
            nameValuePairs.add(new BasicNameValuePair("app_IncomeAfterTax1Period", GlobalData.personalInfo.strIncomeAfterTaxPeriod));
            nameValuePairs.add(new BasicNameValuePair("app_CentrelinkIncome1", GlobalData.personalInfo.strCenterLinkCom));
            nameValuePairs.add(new BasicNameValuePair("app_OtherIncomeSpecify1", GlobalData.personalInfo.strOtherIncomeSpecify));
            nameValuePairs.add(new BasicNameValuePair("app_RentalIncome1", GlobalData.personalInfo.strRentalIncome));
            nameValuePairs.add(new BasicNameValuePair("app_OtherIncomePeriod1", GlobalData.personalInfo.strOtherIncomePeriod));

            //Other information and credit
            nameValuePairs.add(new BasicNameValuePair("app_NameOfPartner1", GlobalData.personalInfo.strNamePartner));
            nameValuePairs.add(new BasicNameValuePair("app_ContactNumber1", GlobalData.personalInfo.strContactNumber));
            nameValuePairs.add(new BasicNameValuePair("app_Hardship1", GlobalData.personalInfo.strHardShip1));
            nameValuePairs.add(new BasicNameValuePair("app_CreditHistory1", GlobalData.personalInfo.strCreditHistory));
            nameValuePairs.add(new BasicNameValuePair("app_totalOutstanding1", GlobalData.personalInfo.strTotalOutstanding));
            nameValuePairs.add(new BasicNameValuePair("app_DateOfDischarge1", GlobalData.personalInfo.strDischargedDate));
            nameValuePairs.add(new BasicNameValuePair("app_DefaultAfterDischarge1", GlobalData.personalInfo.strDefaultAfterDischage));
            nameValuePairs.add(new BasicNameValuePair("app_ExistingClient", GlobalData.personalInfo.strExistingClient));
            
            //Business Detail
			
            nameValuePairs.add(new BasicNameValuePair("Stage", 			GlobalData.personalInfo.strStageBusiness));
            nameValuePairs.add(new BasicNameValuePair("Entity", 		GlobalData.personalInfo.strTypeEntitiy));
            nameValuePairs.add(new BasicNameValuePair("Relationship1", 	GlobalData.personalInfo.strRelationShip1));
            nameValuePairs.add(new BasicNameValuePair("Relationship2", 	GlobalData.personalInfo.strRelationShip2));
            nameValuePairs.add(new BasicNameValuePair("ABN", 			GlobalData.personalInfo.strABNNumber));
            nameValuePairs.add(new BasicNameValuePair("Nature", 		GlobalData.personalInfo.strNatureBusiness));
            nameValuePairs.add(new BasicNameValuePair("Address", 		GlobalData.personalInfo.strBusinessAddress));
            nameValuePairs.add(new BasicNameValuePair("Website", 		GlobalData.personalInfo.strCompanyWebsite));
            nameValuePairs.add(new BasicNameValuePair("MoneyDetail", 	GlobalData.personalInfo.strGiveMoneyDetail));
            nameValuePairs.add(new BasicNameValuePair("Trustee",	 	GlobalData.personalInfo.strNameDirectors));
            nameValuePairs.add(new BasicNameValuePair("Income", 		GlobalData.personalInfo.strBusinessIncome));
            nameValuePairs.add(new BasicNameValuePair("Repay", 			GlobalData.personalInfo.strMostLikeRepay));
            nameValuePairs.add(new BasicNameValuePair("RepayBy", 		GlobalData.personalInfo.strRepayLoanBy));
            nameValuePairs.add(new BasicNameValuePair("Beneficiary", 	GlobalData.personalInfo.strBeneficiary));
            
            nameValuePairs.add(new BasicNameValuePair("CashSale", 	GlobalData.personalInfo.strCashSale));
            nameValuePairs.add(new BasicNameValuePair("EftposSale", GlobalData.personalInfo.strEftposSale));
            nameValuePairs.add(new BasicNameValuePair("UsbYear", 	GlobalData.personalInfo.strUsbYear));
            nameValuePairs.add(new BasicNameValuePair("UsbMonth", 	GlobalData.personalInfo.strUsbMonth));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);
            String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_SIGNUP);
            
            if (str.equals("success")) {
            	k = SEND_SUCCESS;
            }

	    } catch (Exception ex) {
            // TODO Auto-generated catch block
	    	Log.e("HCW", ex.toString());
        }
	    
	    return k;
	}
	
	public Integer fileUpload(String appID, String fileType, String fileName) {
		HttpPost postData = new HttpPost();
		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    
		MultipartEntity reqEntity = new MultipartEntity();
	    int k = UPLOAD_FAIL;
		//Get the text file
		File sdcard = Environment.getExternalStorageDirectory();
		File InputFile = new File(sdcard, fileName);
		
		try {
			if(InputFile.exists()) {
				
				SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(parent);

				String firstName = sharedPreferences.getString("strFirstName1", "");
				String middleName = sharedPreferences.getString("strMiddleName1", "");
				String sureName = sharedPreferences.getString("strSurname1", "");
				
				String strEmailAddress = sharedPreferences.getString("strEMailAddress", "");
				String strMobilePhone = sharedPreferences.getString("strMobilePhone1", "");
				
				String strFullName = firstName + "_" + middleName + "_" + sureName;

				reqEntity.addPart("action", new StringBody("upload"));
				reqEntity.addPart("app_id", new StringBody(appID));
				reqEntity.addPart("photo_type", new StringBody(fileType));
				reqEntity.addPart("file_name", new StringBody(fileName));
				reqEntity.addPart("uploaded_file", new FileBody(InputFile));
				reqEntity.addPart("full_name", new StringBody(strFullName));
				reqEntity.addPart("mail_address", new StringBody(strEmailAddress));
				reqEntity.addPart("mobile_number", new StringBody(strMobilePhone));
				
				postData.setEntity(reqEntity);
			}
			
			postData.setURI(new URI("http://maxfunding.com.au/mobileApp/CRMDB/upload_proc.php"));
//			postData.setURI(new URI("http://www.fairfinance.co.nz/applicationTest/CRMDB/upload_proc.php"));

			response = httpclient.execute(postData);
			
          	String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_FILE_UPLOAD);
            
            if (str.equals("success")) {
            	k = UPLOAD_SUCCESS;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return k;
	}
	
	public String xmlParse(String result, String action) throws XmlPullParserException, IOException {
		
		XmlPullParser parser = Xml.newPullParser();
		String strResult = "fail";
		
	    try {
	    	parser.setInput(new StringReader(result));
	    } catch (XmlPullParserException e) {
	    	// 	TODO Auto-generated catch block
	    	e.printStackTrace();
	    }
	        
        int eventType = parser.getEventType();
 
        String xmlNodeName = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
        	
            switch (eventType) {
	             case XmlPullParser.START_TAG:
	                 xmlNodeName = parser.getName();
	                 break;
	             case XmlPullParser.TEXT:
	            	 if (xmlNodeName.equals("app_id")) {
	            		 GlobalData.personalInfo.strAppID = parser.getText();
	            		 
	            		 Log.e("app_id", GlobalData.personalInfo.strAppID);
	            	 }
	            	 if (xmlNodeName.equals("iDecision")) {
	            		 GlobalData.personalInfo.strDecision = parser.getText();
	            		 Log.e("decision", GlobalData.personalInfo.strDecision);
	            	 }
	            	 if (xmlNodeName.equals(action)) {
	            		 strResult = parser.getText();
	            	 }
	            	 break;
            }
            
            eventType = parser.next();
        }
        
        return strResult;
	}
	
	public Integer usb() {		
		HttpPost httppost = new HttpPost("http://maxfunding.com.au/mobileApp/CRMDB/usb_proc.php");

		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    
	    int k = USB_FAIL;
		try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            
            nameValuePairs.add(new BasicNameValuePair("action", "usb"));
            nameValuePairs.add(new BasicNameValuePair("appID", GlobalData.personalInfo.strAppID));
            
            nameValuePairs.add(new BasicNameValuePair("UsbItem1", GlobalData.personalInfo.strItemList1));
            nameValuePairs.add(new BasicNameValuePair("UsbItem2", GlobalData.personalInfo.strItemList2));
            nameValuePairs.add(new BasicNameValuePair("UsbItem3", GlobalData.personalInfo.strItemList3));
            nameValuePairs.add(new BasicNameValuePair("UsbItem4", GlobalData.personalInfo.strItemList4));
            
            nameValuePairs.add(new BasicNameValuePair("UsbValue1", GlobalData.personalInfo.strCurrentValue1));
            nameValuePairs.add(new BasicNameValuePair("UsbValue2", GlobalData.personalInfo.strCurrentValue2));
            nameValuePairs.add(new BasicNameValuePair("UsbValue3", GlobalData.personalInfo.strCurrentValue3));
            nameValuePairs.add(new BasicNameValuePair("UsbValue4", GlobalData.personalInfo.strCurrentValue4));
            
            nameValuePairs.add(new BasicNameValuePair("guarantor", GlobalData.personalInfo.strGuaranator));
            nameValuePairs.add(new BasicNameValuePair("otherIncomeUSB", GlobalData.personalInfo.strOtherIncomeUSB));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);
			
          	String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_USB);
            
            if (str.equals("success")) {
            	k = USB_SUCCESS;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return k;
	}
	
	public Integer contactUs(String fullName, String phone, String email, String message) {
		HttpPost httppost = new HttpPost("http://www.maxfunding.com.au/mobileApp/CRMDB/contact_us_proc.php");

		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    
	    int k = CONTACT_US_FAIL;
		try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            
            nameValuePairs.add(new BasicNameValuePair("action", "contatc_us"));
            
            nameValuePairs.add(new BasicNameValuePair("full_name", fullName));
            nameValuePairs.add(new BasicNameValuePair("mobile_number", phone));
            nameValuePairs.add(new BasicNameValuePair("mail_address", email));
            nameValuePairs.add(new BasicNameValuePair("message", message));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);
			
          	String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_CONTACT_US);
            
            if (str.equals("success")) {
            	k = CONTACT_US_SUCCESS;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return k;
	}
	
	public Integer helpProc(String strMessage) {
		HttpPost httppost = new HttpPost("http://www.maxfunding.com.au/mobileApp/CRMDB/help_proc.php");

		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    
	    int k = HELP_FAIL;
	    
	    try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            
            nameValuePairs.add(new BasicNameValuePair("action", ACTION_HELP));
            nameValuePairs.add(new BasicNameValuePair("message", strMessage));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);
			
          	String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_HELP);
            
            if (str.equals("success")) {
            	k = HELP_SUCCESS;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	    return k;
	}
	
	public Integer firstFileUpload(String appID, String fullName, String email, String phone, String fileType, String fileName) {
		
		Log.e("test", "firstFileUpload");
		HttpPost postData = new HttpPost();
		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    
	    Log.e("fullName original: ", fullName);
	    
	    //fullName = fullName.replace(" ", "_");
	    Log.e("fullName replace: ", fullName);
		MultipartEntity reqEntity = new MultipartEntity();
	    int k = FIRST_FILE_UPLOAD_FAIL;

		//Get the text file
		File sdcard = Environment.getExternalStorageDirectory();
		File InputFile = new File(sdcard, fileName);
		
		try {
			if(InputFile.exists()) {
				
				SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(parent);
				
				reqEntity.addPart("action", new StringBody("upload"));
				reqEntity.addPart("app_id", new StringBody(appID));
				reqEntity.addPart("photo_type", new StringBody(fileType));
				reqEntity.addPart("file_name", new StringBody(fileName));
				reqEntity.addPart("uploaded_file", new FileBody(InputFile));
				reqEntity.addPart("full_name", new StringBody(fullName));
				reqEntity.addPart("mail_address", new StringBody(email));
				reqEntity.addPart("mobile_number", new StringBody(phone));
				
				postData.setEntity(reqEntity);
			}
			
			postData.setURI(new URI("http://www.maxfunding.com.au/mobileApp/CRMDB/upload_proc.php"));
//			postData.setURI(new URI("http://www.fairfinance.co.nz/applicationTest/CRMDB/upload_proc.php"));

			response = httpclient.execute(postData);
			
          	String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_FILE_UPLOAD);
            
            if (str.equals("success")) {
            	k = FIRST_FILE_UPLOAD_SUCCESS;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return k;
	}
}
